package com.paradox.aggregation.provider.config.dataSource;

import io.seata.rm.datasource.DataSourceProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class DataSourceConfig {

    @Bean("readDataSource")
    @ConfigurationProperties("paradox.datasource.read")
    DataSource readDataSource(DataSourceProperties mainProperties) {
        DataSource dataSource = DataSourceBuilder.create().build();
        /*if (StringUtils.hasText(mainProperties.getName())) {
            dataSource.setPoolName(mainProperties.getName());
        }*/
        return dataSource;
    }

    @Bean("writeDataSource")
    @ConfigurationProperties("paradox.datasource.write")
    DataSource writeDataSource(DataSourceProperties bakProperties) {
        DataSource dataSource = DataSourceBuilder.create().build();
        /*if (StringUtils.hasText(bakProperties.getName())) {
            dataSource.setPoolName(bakProperties.getName());
        }*/
        return dataSource;
    }

    @Primary
    @Bean
    //@DependsOn({ "readDataSource", "writeDataSource"})
    DataSource routingDataSource(DataSource readDataSource,DataSource writeDataSource){
        AbstractRoutingDataSource dataSource=new AbstractRoutingDataSource() {
            @Override
            protected Object determineCurrentLookupKey() {
                return DataSourceSwitcher.LOOKUP_KEY.get();
            }
        };
        dataSource.setDefaultTargetDataSource(readDataSource);
        Map<Object,Object> targetDataSources=new HashMap<>();
        targetDataSources.put("read",readDataSource);
        targetDataSources.put("write",writeDataSource);
        dataSource.setTargetDataSources(targetDataSources);
        dataSource.afterPropertiesSet();
        //return dataSource;
        return new DataSourceProxy(dataSource);
    }

    /*@Primary
    @Bean
    //@DependsOn({ "routingDataSource"})
    DataSource dataSource(AbstractRoutingDataSource routingDataSource){
        return new DataSourceProxy(routingDataSource);
    }*/
}
